﻿using System;
using System.Collections.Generic;
using System.Xml;

namespace MFGLib
{
	public class XmlHelper
	{
		public static string ReadNodeString(XmlNode parent, string name, string defaultValue = null)
		{
			if (parent == null || string.IsNullOrEmpty(name))
			{
				return defaultValue;
			}

			XmlNode node = parent[name];
			if (node == null)
			{
				return defaultValue;
			}

			return node.InnerText;
		}

		public static int ReadNodeInt(XmlNode parent, string name, int defaultValue = 0)
		{
			string value = ReadNodeString(parent, name);
			try
			{
				return Convert.ToInt32(value);
			}
			catch
			{
				return defaultValue;
			}
		}		

		public static double ReadNodeDouble(XmlNode parent, string name, double defaultValue = 0)
		{
			string value = ReadNodeString(parent, name);
			try
			{
				return Convert.ToDouble(value);
			}
			catch
			{
				return defaultValue;
			}
		}

		public static string[] ReadNodeStringArray(XmlNode parent, string name = null)
		{
			if (parent == null)
			{
				return new string[0];
			}

			List<string> items = new List<string>();
			foreach (XmlNode child in parent.ChildNodes)
			{
				if (name == null || child.Name == name)
				{
					items.Add(child.InnerText);
				}
			}

			return items.ToArray();
		}

		public static int[] ReadNodeIntArray(XmlNode parent, string name = null, int defaultValue = 0)
		{
			string[] items = ReadNodeStringArray(parent, name);
			int[] values = new int[items.Length];
			for (int i = 0; i < items.Length; i++)
			{
				int value;
				try
				{
					value = Convert.ToInt32(items[i]);
				}
				catch
				{
					value = defaultValue;
				}
				values[i] = value;
			}

			return values;
		}

		public static double[] ReadNodeDoubleArray(XmlNode parent, string name = null, double defaultValue = 0)
		{
			string[] items = ReadNodeStringArray(parent, name);
			double[] values = new double[items.Length];
			for (int i = 0; i < items.Length; i++)
			{
				double value;
				try
				{
					value = Convert.ToDouble(items[i]);
				}
				catch
				{
					value = defaultValue;
				}
				values[i] = value;
			}

			return values;
		}
	}
}
